package com.aiju.cash.ui.account;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Account;
import com.aiju.cash.R;
import com.aiju.cash.core.api.AccountApi;
import com.aiju.cash.ui.account.adapter.AccountAdapter;
import com.aiju.cash.ui.account.manager.AccountTypeManager;
import com.aiju.cash.util.GsonHelper;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.dialog.AccountDialog;
import com.aiju.widgit.dialog.MemberDialog;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 佐为
 * @date: 2017-03-27 09:56
 * @version: V1.0
 * @Description: 账本列表
 */
public class AccountActivity extends BaseTitleActivity implements SwipeRefreshHelper.OnSwipeRefreshListener, OnLoadMoreListener {

    private TextView creatButton;
    private List<Account> accounts = new ArrayList<>();

    private ListView mListView;

    private AccountAdapter mAccountAdapter;

    private boolean manager;
    private AccountApi accountApi;

    private SwipeRefreshLayout mSryt;
    private SwipeRefreshHelper mSwipeRefreshHelper;

    private int currentNum = 1;
    private int pageSize = 10;
    private boolean isLoad;
    private boolean isRefresh;

    private View emptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        setCenterTitle("记账");

        AccountTypeManager.init();

        accountApi = new AccountApi(mDialogHelper);
        creatButton = (TextView) findViewById(R.id.btn_creat);
        creatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (accounts.size() >= 6) {
                    T.ToastShort("最多只能创建6个账本");
                    return;
                }
                new AccountDialog(AccountActivity.this)
                        .setLayoutParams()
                        .setOnAccount(new AccountDialog.OnAccount() {
                            @Override
                            public void onAccount(String name, int color) {
                                accounts.clear();
                                requsetAccountAdd(name, color);
                            }
                        })
                        .show();
            }
        });

        emptyView = findViewById(R.id.iv_empty);
        mListView = (ListView) findViewById(R.id.lv_swipe_listview);
        mSryt = (SwipeRefreshLayout) this.findViewById(R.id.sryt_swipe_listview);
        mSryt.setColorSchemeColors(getResources().getColor(R.color.app_title_color));

        mAccountAdapter = getAccountAdapter();
        mListView.setAdapter(mAccountAdapter);
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSryt);
        mSwipeRefreshHelper.setOnSwipeRefreshListener(this);
        mSwipeRefreshHelper.setOnLoadMoreListener(this);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(AccountActivity.this, AccountInfoActivity.class);
                intent.putExtra("account", accounts.get(position));
                startActivity(intent);
            }
        });
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAccountAdapter == null) {
                    return;
                }
                if (mAiJuTitleBarView.getRightTitle().equals("取消")) {
                    manager = false;
                    setRightTitle("管理账本");
                    creatButton.setVisibility(View.VISIBLE);
                } else {
                    manager = true;
                    setRightTitle("取消");
                    creatButton.setVisibility(View.GONE);
                }
                mAccountAdapter.setManager(manager);
            }
        });
        requsetAccountList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        accountApi.setDialogHelper(mDialogHelper);
    }

    /**
     * 账本适配器
     *
     * @return
     */
    private AccountAdapter getAccountAdapter() {
        if (mAccountAdapter == null) {
            mAccountAdapter = new AccountAdapter(this, accounts);
            mAccountAdapter.setOnAccountClick(new AccountAdapter.OnAccountClick() {
                @Override
                public void onDelete(final Account account) {
                    new MemberDialog(AccountActivity.this)
                            .setTitileText("是否删除'" + account.getName() + "'账本")
                            .setMsgText("改账本下的所有账本数据将会一并删除并不可恢复。参与共享的用户将不再使用该账本。请谨慎操作！")
                            .setRightText("删除")
                            .setLayoutParams()
                            .setOnSimpleClick(new MemberDialog.OnSimpleClick() {
                                @Override
                                public void onCancel() {

                                }

                                @Override
                                public void onSubmit() {
                                    requsetAccountDelete(account);
                                }
                            })
                            .show();

                }

                @Override
                public void onEdit(Account account) {
                    requsetAccountEdit(account);
                }

                @Override
                public void onShare(Account account) {
                    Intent intent = new Intent(AccountActivity.this, AccountShareActivity.class);
                    intent.putExtra("account", account);
                    startActivity(intent);
                }

                @Override
                public void onDefault(Account account) {
                    if (account.getIsDefault().equals("1")) {
                        return;
                    }
                    requsetAccountDefault(account);
                }
            });
        }
        return mAccountAdapter;
    }

    /**
     * 设置默认账本接口
     *
     * @param account
     */
    private void requsetAccountDefault(final Account account) {
        accountApi.accountSetDefault(account.getId(), new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                T.ToastShort("设置默认账本成功");
                account.setIsDefault("1");
                mUser.getShop().setShopAccount(account);
                mAccountAdapter.setIsDefault(account);
            }
        });
    }

    /**
     * 账本修改
     *
     * @param account
     */
    private void requsetAccountEdit(final Account account) {
        new AccountDialog(AccountActivity.this)
                .setLayoutParams()
                .setAccount(account)
                .setOnAccount(new AccountDialog.OnAccount() {
                    @Override
                    public void onAccount(String name, int color) {
                        requsetAccountEdit(account.getId(), name, "", "", color);
                    }
                }).show();
    }

    /**
     * 账本列表
     */
    private void requsetAccountList() {
        accountApi.accountList(currentNum, pageSize, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                List<Account> list = GsonHelper.convertEntities(data, Account.class);
                if (!Util.isEmpty(list)) {
                    if (isRefresh) {
                        accounts.clear();
                    }
                    accounts.addAll(list);
                }

                if (accounts.size() == 0) {
                    creatButton.setVisibility(View.VISIBLE);
                    creatButton.setText("立即创建");
                    mAiJuTitleBarView.getRightViewContainer().setVisibility(View.INVISIBLE);
                } else {
                    mAiJuTitleBarView.getRightViewContainer().setVisibility(View.VISIBLE);
                    creatButton.setText("创建账本");
                    creatButton.setVisibility(View.VISIBLE);
                }

                if (manager) {
                    manager = false;
                    mAccountAdapter.setManager(manager);
                    setRightTitle("管理账本");
                } else {
                    mAccountAdapter.notifyDataSetChanged();
                }
                completeView(list);
            }
        });
    }

    /**
     * 账本添加
     */
    private void requsetAccountAdd(String name, int color) {
        accountApi.accountAdd(name, color, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                requsetAccountList();
                T.ToastShort("账本添加成功");
            }

            @Override
            protected void onDataFailure(int code, String msg) {
                super.onDataFailure(code, msg);
                T.ToastShort("账本添加失败");
            }
        });
    }

    /**
     * 账本删除
     *
     * @param account
     */
    private void requsetAccountDelete(final Account account) {
        accountApi.accountDelet(account.getId(), new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                accounts.remove(account);
                mAccountAdapter.notifyDataSetChanged();
                if (Util.isEmpty(accounts)) {
                    requsetAccountList();
                }
                if (account.getIsDefault().equals("1")) {
                    mUser.getShop().setShopAccount(null);
                }
                T.ToastShort("账本删除成功");
            }

            @Override
            protected void onDataFailure(int code, String msg) {
                super.onDataFailure(code, msg);
                T.ToastShort("账本删除失败");
            }
        });
    }

    /**
     * 账本修改
     */
    private void requsetAccountEdit(String accountId, String name, String isDefault, String status, int color) {
        accountApi.accountUpdate(accountId, name, isDefault, status, color, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                accounts.clear();
                requsetAccountList();
                T.ToastShort("账本修改成功");
            }

            @Override
            protected void onDataFailure(int code, String msg) {
                super.onDataFailure(code, msg);
                T.ToastShort("账本修改失败");
            }
        });
    }


    @Override
    public void loadMore() {
        isLoad = true;
        currentNum += 1;
        requsetAccountList();
    }

    @Override
    public void onfresh() {
        isRefresh = true;
        currentNum = 1;
        requsetAccountList();
    }

    /**
     * 加载完成视图动作
     *
     * @param blotterLists
     */
    private void completeView(List<Account> blotterLists) {
        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }

        if (blotterLists.size() < pageSize) {
            mSwipeRefreshHelper.setLoadMoreEnable(false);
        } else {
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (mAccountAdapter != null && mSwipeRefreshHelper != null) {
            final boolean emptyViewVisible = mAccountAdapter.isEmpty();
            if (emptyViewVisible) {
                emptyView.setVisibility(View.VISIBLE);
            } else {
                emptyView.setVisibility(View.GONE);
                if (manager) {
                    setRightTitle("取消");
                } else {
                    setRightTitle("管理账本");
                }
            }
        }
    }
}
